(ns poi.excel.utils
  (:use poi.excel))

(defn columns-of-sheet [sheet]
  (into {} (map vector (map get-cell-value (first sheet)) (range))))


(defn sheet-pictures [sheet]
  (into {}
    (keep
      (fn [p]
        (when (instance? org.apache.poi.hssf.usermodel.HSSFPicture p)
          (let [data (.getPictureData p)
                anchor (.getAnchor p)
                row (.getRow1 anchor)
                col (.getCol1 anchor)]
            (when (and (= (inc row) (.getRow2 anchor)) (= (inc col) (.getCol2 anchor)))
              [[row col] data]))))
      (.getDrawingPatriarch sheet))))

(defn copy-sheet-to-another-workbook [sheet1 sheet2]
  (let [wb1 (.getWorkbook sheet1)
        wb2 (.getWorkbook sheet2)
        cached-styles (atom {})
        clone-style (fn [s] (or (get @cached-styles (.getIndex s))
                              (let [ss (create-cell-style wb2)]
                                (.cloneStyleFrom ss s)
                                (swap! cached-styles assoc (.getIndex s) ss)
                                ss)))]
    (dotimes [i (.getLastCellNum (first sheet1))]
      (.setColumnWidth sheet2 i (.getColumnWidth sheet1 i)))
    (doseq [row1 sheet1]
      (let [row2 (create-row sheet2 (.getRowNum row1))]
        (.setHeight row2 (.getHeight row1))
        (doseq [cell1 row1]
          (let [cell2 (create-cell row2 (.getColumnIndex cell1))]
            (set-cell-value cell2 (get-cell-value cell1))
            (set-cell-style cell2 (clone-style (.getCellStyle cell1)))))))
    (doseq [[[row col] data] (sheet-pictures sheet1)]
      (set-cell-image-from-bytes wb2 sheet2 (get-cell! sheet2 row col) (.getData data) (.getPictureType data)))))


;;; old test helpers

(defn fill-sheet [s data]
  (doseq [[ri rdata] (map-indexed vector data)]
    (let [r (create-row s ri)]
      (doseq [[ci cdata] (map-indexed vector rdata)]
        (let [c (create-cell r ci)]
          (set-cell-value c (auto-cell-value cdata)))))))

